<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta http-equiv="X-UA-Compatible" content="ie=edge" />
  <title>Document</title>
</head>

<body>
  <h1>
    编写一个函数，输入n为偶数时，调用函数求1/2+1/4+…+1/n,当输入n为奇数时，调用函数求1+1/3+…+1/n
  </h1>
  <label for="text1"> </label>输入：
  <input type="text" id="text1" />
  <input type="button" id="btn" value="结果" />
  <label for="text2"></label>输入n为偶数时： <input type="text" id="text2" />
  <label for="text3"></label>当输入n为奇数时：
  <input type="text" id="text3" />
</body>
<script>
  var text1 = document.getElementById("text1");
  var text2 = document.getElementById("text2");
  var text3 = document.getElementById("text3");
  var btn = document.getElementById("btn");
  //计算函数
  function sum(x) {
    x = Number(x);
    var count = 0;
    if (x % 2 == 0) {
      for (var i = 1; i <= x; i++) {
        if (i % 2 == 0) {
          count += 1 / i;
        }
      }
      text2.value = count.toFixed(2);
    } else {
      for (var j = 1; j <= x; j++) {
        if (j % 2 != 0) {
          count += 1 / j;
        }
      }
      text3.value = count.toFixed(2);
    }
  }
  btn.onclick = function () {
    text3.value = "";
    text2.value = "";
    sum(text1.value);
  };
</script>

</html>